/**
 * Created by huachuan on 2016/1/4.
 */
angular.module('releasemeetingcontrollers',[])
  //发现的首页（约局）的Controller
  .controller('ReleaseMeetingCtrl',function($scope,$state,$timeout,$cordovaBarcodeScanner,$ionicActionSheet,$cordovaFileTransfer,$cordovaCamera,$cordovaDatePicker,$cordovaImagePicker,Loading,Meeting,ENV,History,Storage,Toast,Wine){
          $scope.picPath = ENV.picPath;
        //顶部提示
        $scope.topTip = '公开约局：发布在约局列表中，所有人都可以报名参加';
        //私密约局：只有@到的用户才受到邀约，才可以报名参加。
        //保存发布约局的信息
        $scope.meeting={
          mm_type:'公开约',//约局类型
          mm_title:'',   //约局主题
          mm_discribe:'',//约局描述
          mm_time:new Date(new Date().getTime()+3600000),    //约局时间
          mm_address:'请选择约局地点', //约局地点
          mm_wine_detail_type:'',//酒款的类型
          mm_wine_detail:'',//具体酒款（1：文本；2：酒款编号集合(用;分隔)）
          mm_pay_type:'我买单',//买单方式
          mm_attend_num:15,//限定人数
          mm_attend_type:'不限',//限定对象（对于公开约类型，这里存放不限、只限男、只限女；对于私密约类型，这里存放被邀会员编号，通过"；"分割）
          shop_id:0,   //约局地点店铺的编号
          mm_img_url:'',//约局的封面
          mm_groupcode_img_url:''//群组的二维码
        }
        //受邀对象的姓名
        $scope.attend_member = [];
        $scope.mm_cover_url = '';//约局封面
        $scope.mm_groupcode_url='';//群组二维码
        $scope.wineSelectedInfo='请选择酒款';
        var isHandInMmAddr = false;
        var isHandInMmWine = false;
        var isUploadMmImg = false;
        var isUploadMmCode = false;
        $scope.$on('$ionicView.beforeEnter',function(){

          //编辑约局的时候
          if(Storage.get('updateMeeting')){

            var updateMeeting = Storage.get('updateMeeting');
            Storage.remove('updateMeeting');
            //$scope.isEditMeeting = true;
            if(updateMeeting.mm_groupcode_img_url&&updateMeeting.mm_groupcode_img_url!=''){
              $scope.edit_groupcode_url = true;
            }else{
              $scope.edit_groupcode_url = false;
            }
            $scope.edit_cover_url = true;
            $scope.update_mm_groupcode_url = updateMeeting.mm_groupcode_img_url;
            $scope.update_mm_cover_url = updateMeeting.mm_img_url;
            var firstIndex = updateMeeting.mm_discribe.indexOf('<br/><br/>以下为手动输入的酒款信息：<br/>');

            $scope.meeting={
              mm_id:updateMeeting.mm_id,
              mm_type:updateMeeting.mm_type,//约局类型
              mm_title:updateMeeting.mm_title,   //约局主题
              mm_time:new Date(updateMeeting.mm_time),    //约局时间
              mm_address:updateMeeting.mm_address, //约局地点
              mm_wine_detail_type:'',//酒款的类型
              mm_wine_detail:'',//具体酒款（1：文本；2：酒款编号集合(用;分隔)）
              mm_pay_type:updateMeeting.mm_pay_type,//买单方式
              mm_attend_num:updateMeeting.mm_attend_num,//限定人数
              mm_attend_type:updateMeeting.mm_attend_type,//限定对象（对于公开约类型，这里存放不限、只限男、只限女；对于私密约类型，这里存放被邀会员编号，通过"；"分割）
              shop_id:updateMeeting.shop_id,   //约局地点店铺的编号
              mm_img_url:updateMeeting.mm_img_url,//约局的封面
              mm_groupcode_img_url:updateMeeting.mm_groupcode_img_url//群组的二维码
            }
            //如果是私密约
            if($scope.meeting.mm_type=='私密约'){
              var attendMemberStr = updateMeeting.mm_attend_type;
              var attendMemberIdList = attendMemberStr.split(";");
              Meeting.findMemberListByIds(attendMemberIdList);
            }
            //对约局描述和手动输入的酒款信息进行拆分
            if(firstIndex!=-1){
              $scope.meeting.mm_discribe=updateMeeting.mm_discribe.substring(0,firstIndex);//约局描述
              Storage.set('wineListContent',updateMeeting.mm_discribe.substring(firstIndex+28));
            }else{
              $scope.meeting.mm_discribe=updateMeeting.mm_discribe;
            }

            var mmUpdateWineList = updateMeeting.mm_wine_detail;
            Meeting.saveMmWineList(mmUpdateWineList);
            if(mmUpdateWineList.length!=0){
              $scope.wineSelectedInfo = '已选择 '+mmUpdateWineList.length+' 款酒';
            }
          }
          //约局的描述内容
          if(Storage.get('mmDesc')){
            Toast.showMessage("填写约局描述内容成功");
            $scope.meeting.mm_discribe = Storage.get('mmDesc');
            Storage.remove('mmDesc');
          }
          //约局的地点
          if(Storage.get('mm_addr_shop')){
            isHandInMmAddr = false;
            Toast.showMessage("选择约局地点成功");
            $scope.meeting.mm_address = Storage.get('mm_addr_shop').shop_detail_addr;
            $scope.meeting.shop_id = Storage.get('mm_addr_shop').shop_id;
            Storage.remove('mm_addr_shop');
          }
          if(Storage.get('mmAddr')){
            isHandInMmAddr = true;
            Toast.showMessage("填写约局地点成功");
            $scope.meeting.mm_address = Storage.get('mmAddr');
            $scope.meeting.shop_id = 0;
            Storage.remove('mmAddr');
          }
          //酒款
          //选择的酒款为在我的收藏或者酒库中搜索的酒款
          //console.log(Meeting.getMmWineList().length);
          if(Meeting.getMmWineList()&& Meeting.getMmWineList().length>0){
            isHandInMmWine = false;
            //Toast.showMessage("选择酒款成功");
            var tempWineIds = '';
           var mmWineList = Meeting.getMmWineList();
           //mmWineList = uniqueWine(mmWineList);
            for(i=0;i<mmWineList.length;i++){
              if(i==mmWineList.length-1){
                tempWineIds +=mmWineList[i].wine_id;
              }else{
                tempWineIds +=mmWineList[i].wine_id+",";
              }
            }
            if(mmWineList.length!=0){
              $scope.wineSelectedInfo = '已选择 '+mmWineList.length+' 款酒';
            }
            $scope.meeting.mm_wine_detail_type = 2;
            $scope.meeting.mm_wine_detail = tempWineIds;
          }else{
            $scope.wineSelectedInfo = "请选择酒款";
            $scope.meeting.mm_wine_detail_type = '';
            $scope.meeting.mm_wine_detail = '';
          }
          if(Meeting.getMmInvitedList()){//受邀对象
            $scope.attend_member = Meeting.getMmInvitedList();
            $scope.meeting.mm_attend_num = $scope.attend_member.length;
            var tempMemberIds = '';
            for(i=0;i<$scope.attend_member.length;i++){
                if(i!=$scope.attend_member.length-1){
                  tempMemberIds +=$scope.attend_member[i].member_id+';';
                }else{
                  tempMemberIds +=$scope.attend_member[i].member_id;
                }
            }
            $scope.meeting.mm_attend_type = tempMemberIds;
          }
        });
      $scope.$on('Meeting.findMemberListByIdsUpdated',function(){
        $scope.attend_member = Meeting.getMemberListJson();
        Meeting.saveMmInvitedList($scope.attend_member);
      });
    //选择约局封面
    var  isMeetingCover = false;
    $scope.selectMeetingCover = function(){
      isMeetingCover = true;
      $ionicActionSheet.show({
        buttons: [
          { text: '拍照' },
          {text: '从手机相册选取'}
        ],
        cancelText: '取消',
        buttonClicked: function (index) {
          if(index==0){
            getPictureFormCamera();
          }else if(index==1){
            getPictureFormAlbums();
          }
          return true;
        }
      });
    };
    //选择群组二维码
    $scope.selectMeetingGroupcode = function(){
      isMeetingCover = false;
      $ionicActionSheet.show({
        buttons: [
          { text: '拍照' },
          {text: '从手机相册选取'}
        ],
        cancelText: '取消',
        buttonClicked: function (index) {
          if(index==0){
            getPictureFormCamera();
          }else if(index==1){
            getPictureFormAlbums();
          }
          return true;
        }
      });
    };
    var uploadServer = encodeURI(ENV.api+"servlet/imageUploadServlet");
    var uploadOptions = new FileUploadOptions();
    uploadOptions.fileKey="file";
    uploadOptions.mimeType="image/jpeg";
    //拍照获取图片
    getPictureFormCamera = function(){
      var options = {
        quality: 30,
        destinationType: Camera.DestinationType.FILE_URI,
        sourceType: Camera.PictureSourceType.CAMERA,
        allowEdit: false,
        encodingType: Camera.EncodingType.JPEG,
        popoverOptions: CameraPopoverOptions,
        saveToPhotoAlbum: true,
        correctOrientation:true
      };
        $cordovaCamera.getPicture(options).then(function(image){
          Toast.showMessage("拍照成功");
          if(isMeetingCover){//约局封面
            $scope.mm_cover_url = image;//约局的封面
            $scope.edit_cover_url = false;
            isUploadMmImg = true;
            console.log($scope.mm_cover_url);
            uploadOptions.fileName=$scope.mm_cover_url.substr($scope.mm_cover_url.lastIndexOf('/')+1);
            $cordovaFileTransfer.upload(uploadServer,$scope.mm_cover_url,uploadOptions)
              .then(function(result){//上传成功
                isUploadMmImg = false;
                if(result.response!='fail'){
                    $scope.meeting.mm_img_url = result.response;
                }
              })
          }else{//群组的二维码
            $scope.mm_groupcode_url = image;
            $scope.edit_groupcode_url = false;
            isUploadMmCode = true;
            uploadOptions.fileName=$scope.mm_groupcode_url.substr($scope.mm_groupcode_url.lastIndexOf('/')+1);
            $cordovaFileTransfer.upload(uploadServer,$scope.mm_groupcode_url,uploadOptions)
              .then(function(result){//上传成功
                isUploadMmCode = false;
                if(result.response!='fail'){
                  $scope.meeting.mm_groupcode_img_url = result.response;
                }
              })
          }
        },function(error){
          Toast.showMessage("拍照取消");
          isUploadMmImg = false;
          isUploadMmCode = false;
        })
    };
    //从手机相册中添加二维码
    getPictureFormAlbums = function() {
      var options = {
        maximumImagesCount: 1,
        quality: 30
      };
      $cordovaImagePicker.getPictures(options)
        .then(function (results) {
          if(isMeetingCover){//约局封面
            if(results.length==0){
              Toast.showMessage("选择图片取消");
            }else{
              $scope.mm_cover_url = results[0];//约局的封面
              $scope.edit_cover_url = false;
              isUploadMmImg = true;
              uploadOptions.fileName=$scope.mm_cover_url.substr($scope.mm_cover_url.lastIndexOf('/')+1);
              $cordovaFileTransfer.upload(uploadServer,$scope.mm_cover_url,uploadOptions)
                .then(function(result){//上传成功
                  isUploadMmImg = false;
                  if(result.response!='fail'){
                    $scope.meeting.mm_img_url = result.response;
                  }
                })
            }
          }else{//群组的二维码
            if(results.length==0){
              Toast.showMessage("选择图片取消");
            }else{
              $scope.mm_groupcode_url = results[0];
              $scope.edit_groupcode_url = false;
              isUploadMmCode = true;
              uploadOptions.fileName=$scope.mm_groupcode_url.substr($scope.mm_groupcode_url.lastIndexOf('/')+1);
              $cordovaFileTransfer.upload(uploadServer,$scope.mm_groupcode_url,uploadOptions)
                .then(function(result){//上传成功
                  isUploadMmCode = false;
                  if(result.response!='fail'){
                    $scope.meeting.mm_groupcode_img_url = result.response;
                  }
                })
            }
          }
          Toast.showMessage("选择图片成功");
        },function(error){
          Toast.showMessage("选择图片取消");
          isUploadMmImg = false;
          isUploadMmCode = false;
        })
    }

    //发布约局
    $scope.releaseMeeting = function(){
        if($scope.meeting.mm_title==''){
          Toast.showMessage("请填写约局主题");
        }else if($scope.meeting.mm_discribe==''){
        Toast.showMessage("请填写约局描述内容");
        }else if($scope.meeting.mm_address=='请选择约局地点'){
          Toast.showMessage("请选择约局地点");
        }else if($scope.meeting.mm_time.getTime()-new Date().getTime()<1800000){
          Toast.showMessage("约局时间与当前时间需间隔30分钟以上");
        }else if(isNaN($scope.meeting.mm_attend_num)||$scope.meeting.mm_attend_num==0||$scope.meeting.mm_attend_num==''){
          Toast.showMessage("请填写正确的限定人数");
        }else if($scope.meeting.mm_type=='私密约'&&!Meeting.getMmInvitedList()){
          Toast.showMessage("请选择受邀对象");
        }else if(isUploadMmImg||isUploadMmCode){
         Toast.showMessage("图片上传中，请稍后");
        }else{
          var cityName ='';
          if(Storage.get("lbsCity")){
            cityName = Storage.get("lbsCity").city_name;
          }
          if($scope.meeting.mm_id&&$scope.meeting.mm_id!=''){//编辑约局
            Loading.showLoading();
            $scope.meeting.member_id = Storage.get("member").member_id;
            $scope.meeting.mm_time = formatDateDetail($scope.meeting.mm_time);
            //手动输入的地址，在前方加入当前定位的城市
            if(isHandInMmAddr){
              $scope.meeting.mm_address = cityName+ $scope.meeting.mm_address;
            }
            //手动输入的酒款信息，在约局描述的后方拼接上
            if(Storage.get('wineListContent')){
              $scope.meeting.mm_discribe = $scope.meeting.mm_discribe+'<br/><br/>以下为手动输入的酒款信息：<br/>'+Storage.get('wineListContent');
            }
            Meeting.updateMeeting($scope.meeting);
          }else{//发布新约局
            Loading.showLoading();
            $scope.meeting.member_id = Storage.get("member").member_id;
            $scope.meeting.mm_time = formatDateDetail($scope.meeting.mm_time);
            if(isHandInMmAddr){
              $scope.meeting.mm_address = cityName+ $scope.meeting.mm_address;
            }
            //手动输入的酒款信息，在约局描述的后方拼接上
            if(Storage.get('wineListContent')){
              $scope.meeting.mm_discribe = $scope.meeting.mm_discribe+'<br/><br/>以下为手动输入的酒款信息：<br/>'+Storage.get('wineListContent');
            }
            Meeting.releaseMeeting($scope.meeting);
          }
        }
      //发布约局的回调
      $scope.$on('Meeting.releaseMeetingResponseUpdated',function(){
        var result = Meeting.getReleaseMeetingJson();
        Loading.hideLoading();
        Toast.showMessage(result.releaseMeetMsg);
        if(result.releaseMeetStatus){
          $timeout(function(){
            $state.transitionTo('tab.discoverIndex');
            $scope.meeting={//清空数据
              mm_type:'公开约',
              mm_title:'',
              mm_discribe:'',
              mm_time:new Date(new Date().getTime()+3600000),
              mm_address:'请选择约局地点',
              mm_wine_detail_type:'',
              mm_wine_detail:'',
              mm_pay_type:'我买单',
              mm_attend_num:15,
              mm_attend_type:'不限',
              shop_id:0,
              mm_img_url:'',
              mm_groupcode_img_url:''
            }
            $scope.mm_groupcode_url = '';
            $scope.mm_cover_url='';
            $scope.attend_member = [];
            $scope.wineSelectedInfo='请选择酒款';
            Meeting.saveMmInvitedList('');
            Meeting.saveMmWineList([]);
            Storage.remove('wineListContent');
            $scope.edit_groupcode_url = false;
            $scope.edit_cover_url = false;
            $scope.update_mm_groupcode_url = '';
            $scope.update_mm_cover_url ='';
            isUploadMmImg = false;
            isUploadMmCode = false;
          },1000);
        }
      });
    }
    //选择约局的类型
    $scope.selectMmType = function(){
      $ionicActionSheet.show({
        buttons: [
          { text: '公开约' },
          { text: '私密约' }
        ],
        titleText: '选择约局的类型',
        cancelText: '取消',
        buttonClicked: function(index) {
          if(index==0){//公开约
            $scope.meeting.mm_type='公开约';
          }else if(index==1){//私密约
            $scope.meeting.mm_type='私密约';
          }
          return true;
        }
      });
    };
    //选择买单方式
    $scope.selectMmPayType = function(){
      $ionicActionSheet.show({
        buttons: [
          { text: '我买单' },
          { text: '你买单' },
          { text: 'AA' }
        ],
        titleText: '选择买单方式',
        cancelText: '取消',
        buttonClicked: function(index) {
          if(index==0){//我买单
            $scope.meeting.mm_pay_type='我买单';
          }else if(index==1){//你买单
            $scope.meeting.mm_pay_type='你买单';
          }else if(index==2){//AA
            $scope.meeting.mm_pay_type='AA';
          }
          return true;
        }
      });
    }
    //选择受邀对象
    $scope.selectMmAttendType = function(){
      $ionicActionSheet.show({
        buttons: [
          { text: '不限' },
          { text: '只限男' },
          { text: '只限女' }
        ],
        titleText: '选择受邀对象',
        cancelText: '取消',
        buttonClicked: function(index) {
          if(index==0){//不限
            $scope.meeting.mm_attend_type='不限';
          }else if(index==1){//只限男
            $scope.meeting.mm_attend_type='只限男';
          }else if(index==2){//只限女
            $scope.meeting.mm_attend_type='只限女';
          }
          return true;
        }
      });
    }

    //填写约局的描述信息
    $scope.go2MeetingDesc = function(){
      console.log($scope.meeting.mm_discribe);
        if($scope.meeting.mm_discribe){
          Storage.set('mmDesc',$scope.meeting.mm_discribe);
        }
      $state.go('release-depict');
    }
    //监听约局类型的编号
    $scope.$watch('meeting.mm_type',function(){
      if($scope.meeting.mm_type=='公开约'){
        $scope.topTip = '公开约局：发布在约局列表中，所有人都可以报名参加';
        $scope.meeting.mm_attend_type = '不限';
      }else if($scope.meeting.mm_type=='私密约'){
        $scope.topTip = '私密约局：只有@到的用户才受到邀约，才可以报名参加';
      }
    });
    //选择约局的时间
    //Android
    $('#selectMmTime').click(function(){
      $(this).mydate({format:"yyyy,MM,dd,HH,mm"},function(date){
        if (!isNaN(date.getTime())) {  // valid date
          $scope.$apply(function () {
            $scope.meeting.mm_time = date;
          });
        }
      },function(){});
    });
    //IOS
   /* $scope.selectMeetingTime = function(){
      var options = {
        date: new Date(new Date().getTime()+3600000),
        mode: 'datetime',
        doneButtonLabel: '确定',
        doneButtonColor: '#000000',
        cancelButtonLabel: '取消',
        cancelButtonColor: '#000000',
      };
      datePicker.show(options, function(d) {
        if (!isNaN(d.getTime())) {  // valid date
          $scope.$apply(function () {
            $scope.meeting.mm_time = d;
          });
        }
      });
    }*/
    //选择约局地点
    $scope.selectMmAddr = function(){
      if($scope.meeting.mm_address!="请选择约局地点"){
        Storage.set('mmAddr',$scope.meeting.mm_address);
      }
      $state.go('select-site-list');
    }
    /****************搜索酒库*****************/
    $scope.selectWine = function(){
      $ionicActionSheet.show({
        buttons: [
          { text: '我的收藏' },
          { text: '扫描酒标' },
          { text: '搜索酒库' },
          { text: '手动输入' }
        ],
        cancelText: '取消',
        buttonClicked: function(index) {
          if(index==0){//我的收藏
              $state.go('my-collect');
          }else if(index==1){//扫描酒标
            openScanBarcode();
          }else if(index==2){//搜索酒库
            $state.go('search-list');
          }else if(index==3){//手动输入
            $state.go('handin_wine');
          }
          return true;
        }
      });
    }

    openScanBarcode = function(){
      $cordovaBarcodeScanner.scan().then(function(imageData) {
        if(imageData.text==null || imageData.text==''){
          Toast.showShortCenter("取消扫描");
        }else{
          Wine.getWineByBarCode(imageData.text);
          $state.transitionTo('barcode-search-list');
        }
      }, function(error) {
        Toast.showShortCenter("扫描条形码失败");
      });
    }
    //点击返回按钮
    $scope.showConfirm = false;
    $scope.goback = function(){
      History.goback();
      //$scope.showConfirm = true;
    }
    /*$scope.cancel = function(){$scope.showConfirm = false;}
    $scope.comfirmLeave = function(){
      $scope.showConfirm = false;
      History.goback();
      $scope.meeting={//清空数据
        mm_type:'公开约',
        mm_title:'',
        mm_discribe:'',
        mm_time:new Date(),
        mm_address:'请选择约局地点',
        mm_wine_detail_type:'',
        mm_wine_detail:'',
        mm_pay_type:'我买单',
        mm_attend_num:15,
        mm_attend_type:'不限',
        shop_id:0,
        mm_img_url:'',
        mm_groupcode_img_url:''
      }
      $scope.mm_groupcode_url = '';
      $scope.mm_cover_url='';
      $scope.attend_member = [];
      $scope.wineSelectedInfo='请选择酒款';
      Meeting.saveMmInvitedList('');
      Meeting.saveMmWineList('');
      Storage.remove('wineListContent');
    }*/
  })
  /************************私密约受邀对象的Controller**************/
  .controller('InviteUserListCtrl',function($scope,$timeout,$state,$location,$ionicScrollDelegate,ENV,Meeting,DiscoverMember,History,Storage,Toast){

    var memberId = Storage.get('member').member_id;
    $scope.picPath = ENV.picPath;
    //搜索的关键字
    $scope.member = {
      searchKey:''
    };
    //选择会员编号
    $scope.selectMember=function(memberId){
      //我关注的列表
      if($scope.memberList.attendMemberList){
        for(i=0;i<$scope.memberList.attendMemberList.length;i++){
          if(memberId==$scope.memberList.attendMemberList[i].member_id){
            //反选
            $scope.memberList.attendMemberList[i].selected = !$scope.memberList.attendMemberList[i].selected;
          }
        }
      }
      //关注我的列表
      if($scope.memberList.beAttendMemberList){
        for(i=0;i<$scope.memberList.beAttendMemberList.length;i++){
          if(memberId==$scope.memberList.beAttendMemberList[i].member_id){
            //反选
            $scope.memberList.beAttendMemberList[i].selected = !$scope.memberList.beAttendMemberList[i].selected;
          }
        }
      }
      //字母索引列表
      if($scope.memberList.wordIndexResultMap){
        for(var temp in $scope.memberList.wordIndexResultMap){
          var arrayList  = $scope.memberList.wordIndexResultMap[temp];
          for(i=0;i<arrayList.length;i++){
            if(memberId==$scope.memberList.wordIndexResultMap[temp][i].member_id){
              $scope.memberList.wordIndexResultMap[temp][i].selected = !$scope.memberList.wordIndexResultMap[temp][i].selected;
            }
          }
        }
      }
      //搜索列表
      if($scope.memberListByKey){
        for(i=0;i<$scope.memberListByKey.length;i++){
          if(memberId ==$scope.memberListByKey[i].member_id){
            $scope.memberListByKey[i].selected = !$scope.memberListByKey[i].selected;
          }
        }
      }
    }
    //点击完成按钮--->选择受邀对象完成
    $scope.finishSelect = function(){
      var selectMemberList = [];
      //我的关注
      if($scope.memberList.attendMemberList){
        for(i=0;i<$scope.memberList.attendMemberList.length;i++){
          if($scope.memberList.attendMemberList[i].selected
            && $scope.memberList.attendMemberList[i].member_id!=memberId){
            selectMemberList.push($scope.memberList.attendMemberList[i]);
          }
        }
      }
      //关注我的会员
      if($scope.memberList.beAttendMemberList){
        for(i=0;i<$scope.memberList.beAttendMemberList.length;i++){
          if($scope.memberList.beAttendMemberList[i].selected
            && $scope.memberList.beAttendMemberList[i].member_id!=memberId){
            selectMemberList.push($scope.memberList.beAttendMemberList[i]);
          }
        }
      }
      //字母索引列表
      if($scope.memberList.wordIndexResultMap){
        for(var temp in $scope.memberList.wordIndexResultMap){
          var arrayList  = $scope.memberList.wordIndexResultMap[temp];
          for(i=0;i<arrayList.length;i++){
            if($scope.memberList.wordIndexResultMap[temp][i].selected
              && $scope.memberList.wordIndexResultMap[temp][i].member_id!=memberId){
              selectMemberList.push($scope.memberList.wordIndexResultMap[temp][i]);
            }
          }
        }
      }
      if(selectMemberList.length>0){
        Meeting.saveMmInvitedList(unique(selectMemberList));
        $state.transitionTo('release-date');
      }else{
          Toast.showMessage("请选择您要邀请的好友");
      }
    }
    $scope.showSearch = false;
    $scope.$watch('member.searchKey',function(){
      $timeout(function(){
        if($scope.member.searchKey!=null && $scope.member.searchKey!=''){//如果搜索信息不为空
          $scope.showSearch = true;
          DiscoverMember.findMemberListByKey($scope.member.searchKey);
        }else{//如果搜索信息为空
          $scope.showSearch = false;
        }
      },500);
    });

    $scope.$on('DiscoverMember.memberListByKeyUpdated',function(){
        $scope.memberListByKey = DiscoverMember.getMemberListJson().memberList;
    });

    //获得会员列表
    DiscoverMember.getAttendMemberList(memberId);
    $scope.$on('DiscoverMember.attendMemberListUpdated',function(){
      $scope.memberList = DiscoverMember.getAttendMemberListJson();
      var invitedMemberList = Meeting.getMmInvitedList();
      if($scope.memberList.attendMemberList && invitedMemberList){
          for(i=0;i<$scope.memberList.attendMemberList.length;i++){
            for(j=0;j<invitedMemberList.length;j++){
                if($scope.memberList.attendMemberList[i].member_id==invitedMemberList[j].member_id){
                  $scope.memberList.attendMemberList[i].selected = true;
                }
            }
          }
      }
      //关注我
      if($scope.memberList.beAttendMemberList && invitedMemberList){
        for(i=0;i<$scope.memberList.beAttendMemberList.length;i++){
          for(j=0;j<invitedMemberList.length;j++){
            if($scope.memberList.beAttendMemberList[i].member_id==invitedMemberList[j].member_id){
              $scope.memberList.beAttendMemberList[i].selected = true;
            }
          }
        }
      }
      //字母索引
      if($scope.memberList.wordIndexResultMap&& invitedMemberList){
        for(var temp in $scope.memberList.wordIndexResultMap){
            var arrayList  = $scope.memberList.wordIndexResultMap[temp];
            for(i=0;i<arrayList.length;i++){
              for(j=0;j<invitedMemberList.length;j++){
                if(arrayList[i].member_id==invitedMemberList[j].member_id){
                  arrayList[i].selected = true;
                }
              }
            }
          }
      }
    });

    //跳转到对应字母的会员列表
    $scope.gotoList = function(id){
      $location.hash(id);
      $ionicScrollDelegate.anchorScroll();
    };
    $scope.goback = function(){History.goback();};//返回

  })





  /*****************选择酒款--->我的收藏的Controller*******************/
  .controller('MeCollectWineCtrl',function($scope,$timeout,$state,ENV,Wine,History,Storage,Meeting,Toast){
      $scope.picPath = ENV.picPath;
      var memberId = Storage.get('member').member_id;
      var  mmWineList = Meeting.getMmWineList();
      //点击复选框选择酒款
      $scope.selectWine = function(index){
        console.log(mmWineList);
        if(!$scope.wineList[index].selected){
          mmWineList.push($scope.wineList[index]);
        }else{
          for(i=0;i<mmWineList.length;i++){
              if(mmWineList[i].wine_id==$scope.wineList[index].wine_id){
                mmWineList.splice(i,1);
              }
          }
        }
        $scope.wineList[index].selected = !$scope.wineList[index].selected;
      }
      //点击完成后，拼接酒款列表
      $scope.finishSelectWine = function(){
       /* var selectedWineList = [];
        if($scope.wineList){
          for(i=0;i<$scope.wineList.length;i++){
            if($scope.wineList[i].selected){
              selectedWineList.push($scope.wineList[i]);
            }
          }
        }*/
       // if(mmWineList&&mmWineList.length!=0){
          Meeting.saveMmWineList(uniqueWine(mmWineList));
          $state.go('release-date');
          $scope.searchKey = '';
       /* }else{
          Toast.showMessage("请选择酒款");
        }*/
      }

      //获取到我收藏的酒款
      Wine.getCollectWineList(memberId);
      $scope.$on('Wine.getCollectWineListUpdated',function(){
          $scope.wineList = Wine.getCollectWineListJson().wineList;
          var hasSelectedWineList = Meeting.getMmWineList();
          if($scope.wineList!=undefined &&$scope.wineList.length!=0
            && hasSelectedWineList!=undefined && hasSelectedWineList.length!=0){
                  for(i=0;i<$scope.wineList.length;i++){
                    for(j=0;j<hasSelectedWineList.length;j++){
                        if($scope.wineList[i].wine_id==hasSelectedWineList[j].wine_id){
                          $scope.wineList[i].selected = true;
                        }
                    }
                  }
          }
      });
    $scope.goback = function(){History.goback()}

    //改变数字的显示，添加逗号分割
    $scope.getFormatNum = function (num) {
      return formatNum(num);
    };

  })
/*****************选择酒款--->搜索酒库的Controller*******************/
  .controller('SearchWineCtrl',function($scope,$timeout,$state,ENV,Wine,History,Meeting,Loading,Toast){
    $scope.searchKey = '';//搜索的关键字
    $scope.wineList = [];
    $scope.picPath = ENV.picPath;
    var  mmWineList = Meeting.getMmWineList();
    Loading.showLoading();
    Wine.getMmWineListByKey($scope.searchKey);
    //搜索酒库
    $scope.$watch('searchKey',function(){
      $timeout(function(){
          Wine.getMmWineListByKey($scope.searchKey);
      },500);
    });
    //加载更多
    $scope.loadMore = function(){
        Wine.getMoreMmWineListByKey($scope.searchKey);
    }
    //是否下一页
    $scope.hasNextPage = function(){
      return Wine.mmWineHasNextPage();
    }
    $scope.$on('Wine.MmWineListByKeyUpdated',function(){
      Loading.hideLoading();
      $scope.wineList = Wine.getMmWineListJson();
      $scope.wineListCount = Wine.getMmWineListCount();
      var hasSelectedWineList = Meeting.getMmWineList();
      if($scope.wineList!=undefined &&$scope.wineList.length!=0
        && hasSelectedWineList!=undefined && hasSelectedWineList.length!=0){
        for(i=0;i<$scope.wineList.length;i++){
          for(j=0;j<hasSelectedWineList.length;j++){
            if($scope.wineList[i].wine_id==hasSelectedWineList[j].wine_id){
              $scope.wineList[i].selected = true;
            }
          }
        }
      }
    });
    $scope.$on('Wine.MoreMmWineListByKeyUpdated',function(){
      $scope.$broadcast('scroll.infiniteScrollComplete');
      var moreWineList = Wine.getMmWineListJson();
      $scope.wineList=$scope.wineList.concat(moreWineList);
      var hasSelectedWineList = Meeting.getMmWineList();
      if($scope.wineList!=undefined &&$scope.wineList.length!=0
        && hasSelectedWineList!=undefined && hasSelectedWineList.length!=0){
        for(i=0;i<$scope.wineList.length;i++){
          for(j=0;j<hasSelectedWineList.length;j++){
            if($scope.wineList[i].wine_id==hasSelectedWineList[j].wine_id){
              $scope.wineList[i].selected = true;
            }
          }
        }
      }
    });
    //点击复选框选择酒款
    $scope.selectWine = function(index){
      if(!$scope.wineList[index].selected){
        mmWineList.push($scope.wineList[index]);
      }else{
        for(i=0;i<mmWineList.length;i++){
          if(mmWineList[i].wine_id==$scope.wineList[index].wine_id){
            mmWineList.splice(i,1);
          }
        }
      }
      $scope.wineList[index].selected = !$scope.wineList[index].selected;
    }
    //点击完成后，拼接酒款列表
    $scope.finishSelectWine = function(){
     /* var selectedWineList = [];
      if($scope.wineList){
        for(i=0;i<$scope.wineList.length;i++){
          if($scope.wineList[i].selected){
            selectedWineList.push($scope.wineList[i]);
          }
        }
      }*/
     // if(mmWineList&&mmWineList.length!=0){
       /* var mmWineList = Meeting.getMmWineList();
        if(mmWineList!=undefined&&mmWineList!=''){
          mmWineList = mmWineList.concat(selectedWineList);
        }else{
          mmWineList = selectedWineList;
        }*/
        Meeting.saveMmWineList(uniqueWine(mmWineList));
        $state.go('release-date');
        $scope.searchKey = '';
     /* }else{
        Toast.showMessage("请选择酒款");
      }*/
    }
    $scope.goback = function(){History.goback();};//返回
    //改变数字的显示，添加逗号分割
    $scope.getFormatNum = function (num) {
      return formatNum(num);
    };
  })
/*********************选择酒款---->扫描酒标****************************/
  .controller('BarCodeSearchWineCtrl',function($scope,$state,ENV,Wine,Meeting,History){
    var  mmWineList = Meeting.getMmWineList();

    $scope.$on('Wine.WineSearchUpdated',function(){
      $scope.wineList = Wine.getWineListJson().wineList;
      var hasSelectedWineList = Meeting.getMmWineList();
      if($scope.wineList!=undefined &&$scope.wineList.length!=0
        && hasSelectedWineList!=undefined && hasSelectedWineList.length!=0){
        for(i=0;i<$scope.wineList.length;i++){
          for(j=0;j<hasSelectedWineList.length;j++){
            if($scope.wineList[i].wine_id==hasSelectedWineList[j].wine_id){
              $scope.wineList[i].selected = true;
            }
          }
        }
      }
    });
    //点击复选框选择酒款
    $scope.selectWine = function(index){
      if(!$scope.wineList[index].selected){
        mmWineList.push($scope.wineList[index]);
      }else{
        for(i=0;i<mmWineList.length;i++){
          if(mmWineList[i].wine_id==$scope.wineList[index].wine_id){
            mmWineList.splice(i,1);
          }
        }
      }
      $scope.wineList[index].selected = !$scope.wineList[index].selected;
    }
    $scope.goback = function(){
      History.goback();
    }
    //点击完成后
    $scope.finishSelectWine = function(){
      /*var selectedWineList = [];
      if($scope.wineList){
        for(i=0;i<$scope.wineList.length;i++){
          if($scope.wineList[i].selected){
            selectedWineList.push($scope.wineList[i]);
          }
        }
      }*/
      if(mmWineList&&mmWineList.length!=0){
        /*var mmWineList = Meeting.getMmWineList();
        if(mmWineList!=undefined&&mmWineList!=''){
          mmWineList = mmWineList.concat(selectedWineList);
        }else{
          mmWineList = selectedWineList;
        }
        mmWineList = uniqueWine(mmWineList);*/
        Meeting.saveMmWineList(uniqueWine(mmWineList));
      }
      $state.go('release-date');
    };
    //改变数字的显示，添加逗号分割
    $scope.getFormatNum = function (num) {
      return formatNum(num);
    };
  })
/*****************选择酒款--->手动输入的Controller*******************/
  .controller('HandInWineCtrl',function($scope,$timeout,$state,ENV,Shop,History,Storage){

    $scope.wine= {
      handIn:Storage.get('wineListContent')
    };
    Storage.remove('wineListContent');
    $scope.finishSelectWine = function(){
      if($scope.wine.handIn){
        Storage.set('wineListContent',$scope.wine.handIn);
        $state.go('release-date');
      }else{
        Toast.showMessage("请填写约局酒款信息");
      }
    };

    $scope.goback = function(){History.goback();};//返回

    //改变数字的显示，添加逗号分割
    $scope.getFormatNum = function (num) {
      return formatNum(num);
    };
  })


/**************************选择约局地点的controller****************/
  .controller('ReleaseMeetingAddrCtrl',function($scope,$timeout,$state,ENV,Shop,History,Storage,Toast){
    $scope.goback = function(){History.goback();};//返回
    var city = Storage.get('lbsCity');
    $scope.picPath = ENV.picPath;
    $scope.addr={
      mmAddr:Storage.get('mmAddr')
    };
    Storage.remove('mmAddr');
    //清空约局地点
    $scope.clearAddr = function(){
      $scope.addr.mmAddr = '';
    }
    //获取所有的店铺信息
    if(city!=undefined && city!=''){
      Shop.getShopListByKey('',city.province_id,city.shop_city_id);
    }else{
      Shop.getShopListByKey('');
    }
    $scope.insertMmAddr = function(){
      if($scope.addr.mmAddr==''){
        Toast.showMessage("请输入约局地点");
      }else{
        Storage.set('mmAddr',$scope.addr.mmAddr);
        $state.go('release-date');
      }
    }
    $scope.$watch('addr.mmAddr',function(){//根据输入的信息进行搜索
      $timeout(function(){
        //根据输入的关键字查找相应的店铺
          Shop.getShopListByKey($scope.addr.mmAddr);
      },500);
    });
    $scope.$on('Shop.shopListUpdated',function(){
        $scope.$broadcast('scroll.infiniteScrollComplete');
        $scope.shopList = Shop.getShopListJson();
    });
    //加载更多店铺的信息
    $scope.loadMore = function(){
      if($scope.addr.mmAddr!=''){
        Shop.getMoreShopListByKey($scope.addr.mmAddr);
      }else if(city!=undefined&&city!=''){
        Shop.getMoreShopListByKey('',city.province_id,city.shop_city_id);
      }else{
        Shop.getMoreShopListByKey('','','');
      }
    }
    //是否有下一页
    $scope.hasNextPage = function(){
      return Shop.hasNextPage();
    }

    $scope.selectShop = function(index){
      var selectShop = $scope.shopList[index];
      Storage.set("mm_addr_shop",selectShop);
      $state.go('release-date');
    }
    /*//选择约局的地点
    $scope.selectMmAddr = function(index){
        for(i=0;i<$scope.shopList.length;i++){
          $scope.shopList[i].selected = false;
        }
      $scope.shopList[index].selected = true;
    }
    //确认所选择的约局地点
    $scope.selectShop = function(){
      var selectShop = '';
      for(i=0;i<$scope.shopList.length;i++){
          if($scope.shopList[i].selected){
            selectShop = $scope.shopList[i];
          }
      }
      if(selectShop==''){
          Toast.showMessage("请选择约局地点");
      }else{
        Storage.set("mm_addr_shop",selectShop);
        $state.go('release-date');
      }
    }*/
  })
  /****************约局描述内容controller******************/
  .controller('ReleaseDescCtrl',function($scope,$state,History,Storage,Toast){
      $scope.goback = function(){
        History.goback();
      }
       $scope.meeting = {
        mmDesc:Storage.get('mmDesc')
      };
      $scope.descFinish = function(){
          if($scope.meeting.mmDesc==''){
            Toast.showMessage("请填写约局描述内容");
          }else{
            Storage.set("mmDesc",$scope.meeting.mmDesc);
            $state.go('release-date');
          }
      }
  })
